package com.rongxun.api;

import android.app.Application;

import com.rongxun.api.config.APIConfig;
import com.rongxun.api.dao.response.UIConfiguration;
import com.rongxun.api.utils.FlyLog;
import com.rongxun.api.utils.PreferenceUtils;
import com.rongxun.api.utils.RxUtil;

import java.util.HashMap;
import java.util.Map;

import io.reactivex.Flowable;


/**
 * 创建者     庄丰泽
 * 创建时间   2018/5/18 13:45
 * 描述	      网络请求实现类
 * <p>
 */


public class ApiManager {

    private static final String TAG = "ApiManager";

    public static volatile ApiManager retrofitManager;

    public static Application mContext;


    public static ApiManager getInstance() {
        if (retrofitManager == null) {
            synchronized (ApiManager.class) {
                if (retrofitManager == null) {
                    retrofitManager = new ApiManager();
                }
            }
        }
        return retrofitManager;
    }

    public void init(Application application) {
        if (mContext == null) {
            mContext = application;
            PreferenceUtils.init(application);
        }
    }

    public static ApiService getApiService() {
        return getService(UserInfoManager.getInstance(mContext).getServers_url().isEmpty() ? APIConfig.getHost() : UserInfoManager.getInstance(mContext).getServers_url(), ApiService.class);
    }


    public static ApiService getApiMt4Service() {
        return getService(APIConfig.DAILY_URL, ApiService.class);
    }


    public static ApiService getLoginService() {
        return getService(APIConfig.DAILY_URL_CEO, ApiService.class);
    }


    public static <T> T getService(String baseUrl, Class<T> cls) {

        return Api.with(baseUrl).getService(cls);

    }


    public static void release() {
        PreferenceUtils.release();
    }


    public Flowable<UIConfiguration> getUIConfiguration() {

        String versionName = AppSysInfoManager.getInstance().getVersionName();
        String channel = AppSysInfoManager.getInstance().getChannel();
        String packageName = AppSysInfoManager.getInstance().getPackageName();


        Map<String, String> map = new HashMap<>();

        map.put("appVersion", versionName);
        map.put("channelName", channel == null ? "channelregistertest1" : channel);
        map.put("appPackage", packageName);
        map.put("packageName", packageName);

        for (Map.Entry<String, String> en : map.entrySet()) {

            FlyLog.d("Key: " + en.getKey() + ", Value: " + en.getValue());

        }


        return getApiMt4Service().getUIConfiguration(map).compose(RxUtil.handleResult()).compose(RxUtil.rxSchedulerHelper());

    }
}


